package com.ppandroid.wifiap

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.ppandroid.wifiap.adapter.ConnectedDevicesAdapter
import com.ppandroid.wifiap.databinding.ActivityMainBinding
import com.ppandroid.wifiap.manager.HotspotResult
import com.ppandroid.wifiap.manager.HttpServerManager
import com.ppandroid.wifiap.manager.PermissionManager
import com.ppandroid.wifiap.manager.WifiHotspotManager
import com.ppandroid.wifiap.model.ConnectedDevice
import com.ppandroid.wifiap.util.QrCodeGenerator
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class MainActivity : AppCompatActivity() {
    
    private lateinit var binding: ActivityMainBinding
    private lateinit var wifiHotspotManager: WifiHotspotManager
    private lateinit var httpServerManager: HttpServerManager
    private lateinit var permissionManager: PermissionManager
    private lateinit var devicesAdapter: ConnectedDevicesAdapter
    
    private var isHotspotRunning = false
    private var updateJob: kotlinx.coroutines.Job? = null
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)
        
        initManagers()
        initViews()
        checkPermissions()
        setupHotspotSwitch()
        startPeriodicUpdates()
    }
    
    private fun initManagers() {
        wifiHotspotManager = WifiHotspotManager(this)
        httpServerManager = HttpServerManager()
        httpServerManager.wifiHotspotManager = wifiHotspotManager
        httpServerManager.onAccessCallback = {
            updateAccessCount(it)
        }
        permissionManager = PermissionManager(this)
    }
    
    private fun initViews() {
        // 初始化RecyclerView
        devicesAdapter = ConnectedDevicesAdapter()
        binding.rvConnectedDevices.apply {
            layoutManager = LinearLayoutManager(this@MainActivity)
            adapter = devicesAdapter
        }
        
        // 设置刷新按钮点击事件
        binding.fabRefresh.setOnClickListener {
            // 添加旋转动画
            val rotateAnimation = android.view.animation.RotateAnimation(
                0f, 360f,
                android.view.animation.Animation.RELATIVE_TO_SELF, 0.5f,
                android.view.animation.Animation.RELATIVE_TO_SELF, 0.5f
            ).apply {
                duration = 1000
                interpolator = android.view.animation.LinearInterpolator()
            }
            binding.fabRefresh.startAnimation(rotateAnimation)
            
            // 刷新数据
            updateHotspotInfo()
            updateConnectedDevices()
            updateQrCode()
            
            // 显示提示
            Toast.makeText(this, "刷新成功", Toast.LENGTH_SHORT).show()
        }
        
        // 设置初始状态
        updateHotspotInfo()
        updateConnectedDevices()
        updateQrCode()
    }
    
    private fun checkPermissions() {
        if (!permissionManager.hasRequiredPermissions()) {
            requestPermissions()
        }
    }
    
    private fun requestPermissions() {
        permissionManager.requestPermissions { allGranted, grantedList, deniedList ->
            if (allGranted) {
                Toast.makeText(
                    this@MainActivity,
                    "所有权限已授予",
                    Toast.LENGTH_SHORT
                ).show()
            } else {
                Toast.makeText(
                    this@MainActivity,
                    "以下权限被拒绝: $deniedList",
                    Toast.LENGTH_LONG
                ).show()
            }
        }
    }
    
    private fun setupHotspotSwitch() {
        binding.switchWifiAp.setOnCheckedChangeListener { _, isChecked ->
            if (isChecked) {
                startHotspot()
            } else {
                stopHotspot()
            }
        }
    }
    
    private fun startHotspot() {
        startPeriodicUpdates()
        lifecycleScope.launch {
            try {
                when (val result = wifiHotspotManager.startHotspot()) {
                    is HotspotResult.Success -> {
                        isHotspotRunning = true
                        binding.switchWifiAp.isChecked = true
                        showHotspotInfo()
                        startHttpServer()
                        Toast.makeText(
                            this@MainActivity,
                            "WiFi热点已启动",
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                    is HotspotResult.NeedUserAction -> {
                        // 新增判断：如果用户已经手动开启热点，则不弹窗
                        if (wifiHotspotManager.isHotspotRunning()) {
                            isHotspotRunning = true
                            binding.switchWifiAp.isChecked = true
                            showHotspotInfo()
                            startHttpServer()
                            Toast.makeText(
                                this@MainActivity,
                                "WiFi热点已启动（已手动开启）",
                                Toast.LENGTH_SHORT
                            ).show()
                        } else {
                            binding.switchWifiAp.isChecked = false
                            showHotspotUserActionDialog()
                        }
                    }
                    is HotspotResult.Error -> {
                        binding.switchWifiAp.isChecked = false
                        Toast.makeText(
                            this@MainActivity,
                            result.message,
                            Toast.LENGTH_SHORT
                        ).show()
                    }
                }
            } catch (e: Exception) {
                binding.switchWifiAp.isChecked = false
                Toast.makeText(
                    this@MainActivity,
                    "启动热点时发生错误: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun showHotspotUserActionDialog() {
        androidx.appcompat.app.AlertDialog.Builder(this)
            .setTitle("需要手动开启热点")
            .setMessage("由于系统限制，请前往系统设置手动开启WiFi热点。")
            .setPositiveButton("去设置") { _, _ ->
                try {
                    startActivity(android.content.Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS))
                } catch (e: Exception) {
                    Toast.makeText(this, "无法打开设置界面", Toast.LENGTH_SHORT).show()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }
    
    private fun stopHotspot() {
        stopPeriodicUpdates()
        lifecycleScope.launch {
            try {
                val success = wifiHotspotManager.stopHotspot()
                if (success) {
                    isHotspotRunning = false
                    binding.switchWifiAp.isChecked = false
                    hideHotspotInfo()
                    stopHttpServer()
                    Toast.makeText(
                        this@MainActivity,
                        "WiFi热点已停止",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    binding.switchWifiAp.isChecked = true
                    Toast.makeText(
                        this@MainActivity,
                        "停止热点失败",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            } catch (e: Exception) {
                binding.switchWifiAp.isChecked = true
                Toast.makeText(
                    this@MainActivity,
                    "停止热点时发生错误: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
    
    private fun startHttpServer() {
        lifecycleScope.launch {
            try {
                val success = httpServerManager.startServer()
                if (success) {
                    updateQrCode()
                    Toast.makeText(
                        this@MainActivity,
                        "HTTP服务器已启动",
                        Toast.LENGTH_SHORT
                    ).show()
                } else {
                    Toast.makeText(
                        this@MainActivity,
                        "启动HTTP服务器失败",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            } catch (e: Exception) {
                Toast.makeText(
                    this@MainActivity,
                    "启动HTTP服务器时发生错误: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
    
    private fun stopHttpServer() {
        lifecycleScope.launch {
            try {
                httpServerManager.stopServer()
                hideQrCode()
                Toast.makeText(
                    this@MainActivity,
                    "HTTP服务器已停止",
                    Toast.LENGTH_SHORT
                ).show()
            } catch (e: Exception) {
                Toast.makeText(
                    this@MainActivity,
                    "停止HTTP服务器时发生错误: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }
    
    private fun showHotspotInfo() {
        binding.cardHotspotInfo.visibility = View.VISIBLE
        binding.cardConnectedDevices.visibility = View.VISIBLE
        binding.cardQrCode.visibility = View.VISIBLE
        updateHotspotInfo()
    }
    
    private fun hideHotspotInfo() {
        binding.cardHotspotInfo.visibility = View.GONE
        binding.cardConnectedDevices.visibility = View.GONE
        binding.cardQrCode.visibility = View.GONE
        devicesAdapter.clearDevices()
    }
    
    private fun hideQrCode() {
        binding.cardQrCode.visibility = View.GONE
    }
    
    private fun updateHotspotInfo() {
        val ssid = wifiHotspotManager.getHotspotSsid()
        val pwd = wifiHotspotManager.getHotspotPassword()
        val localIp = wifiHotspotManager.getLocalIpAddress()
        val canGetRealSsid = ssid != WifiHotspotManager.SSID
        val canGetRealPwd = pwd != WifiHotspotManager.PASSWORD
        binding.tvSsid.text = if (canGetRealSsid) ssid else "(无法获取)"
        binding.tvPassword.text = if (canGetRealPwd) pwd else "(无法获取)"
        binding.tvLocalIp.text = localIp
        binding.btnGotoHotspotSettings.visibility = if (!canGetRealSsid || !canGetRealPwd) View.VISIBLE else View.GONE
        binding.btnGotoHotspotSettings.setOnClickListener {
            try {
                startActivity(android.content.Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS))
            } catch (e: Exception) {
                Toast.makeText(this, "无法打开设置界面", Toast.LENGTH_SHORT).show()
            }
        }
    }
    
    private fun updateConnectedDevices() {
        lifecycleScope.launch(Dispatchers.IO) {
            val devices = getConnectedDevicesFromArpTable()
            withContext(Dispatchers.Main) {
                devicesAdapter.updateDevices(devices)
                // 更新设备计数
                binding.tvDeviceCount.text = "${devices.size} 台设备"
                // 如果没有设备，显示提示信息
                if (devices.isEmpty()) {
                    binding.tvNoDevices.visibility = View.VISIBLE
                } else {
                    binding.tvNoDevices.visibility = View.GONE
                }
            }
        }
    }

    // 监听网络变化，自动刷新设备列表（可选：也可用BroadcastReceiver实现更及时刷新）
    // 这里只做定时刷新，已在startPeriodicUpdates里实现


    private fun getConnectedDevicesFromArpTable(): List<ConnectedDevice> {
        val devices = mutableListOf<ConnectedDevice>()
        try {
            java.io.BufferedReader(java.io.FileReader("/proc/net/arp")).use { br ->
                br.readLine() // Skip header
                var line: String?
                while (br.readLine().also { line = it } != null) {
                    val parts = line?.split(Regex("\\s+"))?.filter { it.isNotEmpty() }
                    if (parts != null && parts.size >= 4) {
                        val ipAddress = parts[0]
                        val macAddress = parts[3]
                        if (macAddress != "00:00:00:00:00:00") {
                            devices.add(ConnectedDevice("Unknown", macAddress, ipAddress))
                        }
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return devices
    }
    
    private fun updateAccessCount(count: Int) {
        binding.tvAccessCount.text = "访问次数: $count"
    }


    private fun stopPeriodicUpdates() {
        updateJob?.cancel()
        updateJob = null
    }

    private fun updateQrCode() {
        lifecycleScope.launch(Dispatchers.IO) {
            try {
                val serverUrl = httpServerManager.getServerUrl()
                val qrCodeBitmap = QrCodeGenerator.generateQrCode(serverUrl, 400, 400)
                withContext(Dispatchers.Main) {
                    if (qrCodeBitmap != null) {
                        binding.ivQrCode.setImageBitmap(qrCodeBitmap)
                    }
                    binding.tvQrInterfaceUrl.text = serverUrl
                }
            } catch (e: Exception) {
                withContext(Dispatchers.Main) {
                    Toast.makeText(
                        this@MainActivity,
                        "生成二维码失败: ${e.message}",
                        Toast.LENGTH_SHORT
                    ).show()
                }
            }
        }
    }
    
    private fun startPeriodicUpdates() {
        lifecycleScope.launch {
            while (true) {
                try {
                    if (isHotspotRunning) {
                        updateAccessCount()
                        updateConnectedDevices()
                    }
                    kotlinx.coroutines.delay(5000) // 每5秒更新一次
                } catch (e: Exception) {
                    // 忽略错误，继续更新
                }
            }
        }
    }
    
    private fun updateAccessCount() {
        val accessCount = httpServerManager.getAccessCount()
        binding.tvAccessCount.text = "访问次数: $accessCount"
    }
    
    override fun onDestroy() {
        super.onDestroy()
        lifecycleScope.launch {
            if (isHotspotRunning) {
                stopHotspot()
            }
        }
    }
}
